import { ref } from 'vue'
import type { Ref } from 'vue'

// PDF导出配置接口
export interface PDFExportOptions {
  filename?: string
  orientation?: 'portrait' | 'landscape'
  format?: 'a4' | 'a3' | 'a5' | 'letter'
  scale?: number
  quality?: number
  backgroundColor?: string
  margin?: {
    top?: number
    bottom?: number
    left?: number
    right?: number
  }
  pageBreak?: boolean
  excludeElements?: string[]
}

// PDF导出结果接口
export interface PDFExportResult {
  success: boolean
  filename: string
  blob?: Blob
  url?: string
  error?: string
}

// 颜色转换工具
const oklchToRgb = (oklchString: string): string => {
  try {
    // 简单实现oklch到rgb的转换
    // 这里简化处理，实际项目中可能需要更精确的转换
    const match = oklchString.match(/oklch\(([^)]+)\)/)
    if (!match) return oklchString
    
    const values = match[1].split(/\s+/).map(v => parseFloat(v))
    if (values.length < 3) return oklchString
    
    // 简化的转换逻辑，实际使用时可能需要更复杂的算法
    const [l, c, h] = values
    const a = 1 // 假设alpha为1
    
    // 这里使用简化的转换，实际项目中应使用专业的颜色转换库
    const r = Math.round(Math.max(0, Math.min(255, l * 255)))
    const g = Math.round(Math.max(0, Math.min(255, l * 255 + c * Math.cos(h * Math.PI / 180) * 50)))
    const b = Math.round(Math.max(0, Math.min(255, l * 255 + c * Math.sin(h * Math.PI / 180) * 50)))
    
    return `rgb(${r}, ${g}, ${b})`
  } catch (error) {
    console.warn('颜色转换失败:', error)
    return oklchString
  }
}

// 深度替换oklch颜色
const deepReplaceOklchColors = (element: HTMLElement): void => {
  if (!element || typeof window === 'undefined') return
  
  const computed = window.getComputedStyle(element)
  const properties = ['color', 'background-color', 'border-color', 'fill', 'stroke']
  
  properties.forEach(prop => {
    try {
      const value = computed.getPropertyValue(prop)
      if (value && value.includes('oklch')) {
        const rgbValue = oklchToRgb(value)
        element.style.setProperty(prop, rgbValue)
      }
    } catch (error) {
      console.warn(`处理属性 ${prop} 失败:`, error)
    }
  })
  
  // 递归处理子元素
  Array.from(element.children).forEach(child => {
    if (child instanceof HTMLElement) {
      deepReplaceOklchColors(child)
    }
  })
}

// 创建PDF导出工具
export const usePDFExport = () => {
  const isGenerating: Ref<boolean> = ref(false)
  const progress: Ref<number> = ref(0)

  /**
   * 导出HTML元素为PDF
   * @param elementRef - 要导出的HTML元素引用
   * @param options - PDF导出配置选项
   * @returns Promise<PDFExportResult>
   */
  const exportToPDF = async (
    elementRef: HTMLElement | null,
    options: PDFExportOptions = {}
  ): Promise<PDFExportResult> => {
    const result: PDFExportResult = {
      success: false,
      filename: '',
    }

    // 检查环境
    if (typeof window === 'undefined') {
      result.error = 'PDF导出功能仅在浏览器环境中可用'
      return result
    }

    if (!elementRef) {
      result.error = '未找到要导出的元素'
      return result
    }

    // 设置默认选项
    const opts = {
      filename: options.filename || `导出文件_${new Date().toISOString().slice(0, 10)}.pdf`,
      orientation: options.orientation || 'portrait',
      format: options.format || 'a4',
      scale: options.scale || 2,
      quality: options.quality || 1.0,
      backgroundColor: options.backgroundColor || '#ffffff',
      margin: {
        top: options.margin?.top || 10,
        bottom: options.margin?.bottom || 10,
        left: options.margin?.left || 10,
        right: options.margin?.right || 10,
      },
      pageBreak: options.pageBreak !== false,
      excludeElements: options.excludeElements || [],
      ...options,
    }

    isGenerating.value = true
    progress.value = 0

    try {
      // 动态导入依赖
      const [{ default: jsPDF }, { default: html2canvas }] = await Promise.all([
        import('jspdf'),
        import('html2canvas'),
      ])

      // 创建内容克隆
      const clone = elementRef.cloneNode(true) as HTMLElement
      clone.style.position = 'absolute'
      clone.style.top = '-9999px'
      clone.style.left = '-9999px'
      clone.style.width = '794px' // A4宽度像素值
      clone.style.backgroundColor = opts.backgroundColor
      
      // 处理排除元素
      opts.excludeElements.forEach(selector => {
        const elements = clone.querySelectorAll(selector)
        elements.forEach(el => el.remove())
      })

      document.body.appendChild(clone)

      // 处理颜色转换
      progress.value = 10
      deepReplaceOklchColors(clone)

      // 等待渲染
      await new Promise(resolve => setTimeout(resolve, 100))
      progress.value = 20

      // 使用html2canvas捕获内容
      const canvas = await html2canvas(clone, {
        scale: opts.scale,
        useCORS: true,
        backgroundColor: opts.backgroundColor,
        logging: false,
        width: 794,
        height: 1123, // A4高度像素值
      })

      document.body.removeChild(clone)
      progress.value = 60

      // 创建PDF
      const pdf = new jsPDF({
        orientation: opts.orientation,
        unit: 'mm',
        format: opts.format,
      })

      // 计算尺寸
      const imgData = canvas.toDataURL('image/jpeg', opts.quality)
      const pageWidth = pdf.internal.pageSize.getWidth()
      const pageHeight = pdf.internal.pageSize.getHeight()
      
      const imgWidth = pageWidth - opts.margin.left - opts.margin.right
      const imgHeight = (canvas.height * imgWidth) / canvas.width

      // 处理分页
      if (imgHeight > pageHeight - opts.margin.top - opts.margin.bottom && opts.pageBreak) {
        // 需要分页
        const pageCount = Math.ceil(imgHeight / (pageHeight - opts.margin.top - opts.margin.bottom))
        const sliceHeight = canvas.height / pageCount
        
        for (let i = 0; i < pageCount; i++) {
          if (i > 0) pdf.addPage()
          
          const sliceCanvas = document.createElement('canvas')
          sliceCanvas.width = canvas.width
          sliceCanvas.height = sliceHeight
          
          const ctx = sliceCanvas.getContext('2d')
          if (ctx) {
            ctx.drawImage(
              canvas,
              0, i * sliceHeight, canvas.width, sliceHeight,
              0, 0, sliceCanvas.width, sliceCanvas.height
            )
          }
          
          const sliceImgData = sliceCanvas.toDataURL('image/jpeg', opts.quality)
          pdf.addImage(
            sliceImgData,
            'JPEG',
            opts.margin.left,
            opts.margin.top,
            imgWidth,
            (sliceHeight * imgWidth) / canvas.width
          )
        }
      } else {
        // 单页
        pdf.addImage(
          imgData,
          'JPEG',
          opts.margin.left,
          opts.margin.top,
          imgWidth,
          imgHeight
        )
      }

      // 保存PDF
      pdf.save(opts.filename)
      
      // 创建Blob URL（可选）
      const pdfBlob = pdf.output('blob')
      const pdfUrl = URL.createObjectURL(pdfBlob)
      
      result.success = true
      result.filename = opts.filename
      result.blob = pdfBlob
      result.url = pdfUrl
      
      progress.value = 100

    } catch (error) {
      console.error('PDF导出失败:', error)
      result.error = error instanceof Error ? error.message : '导出失败'
    } finally {
      isGenerating.value = false
    }

    return result
  }

  /**
   * 导出页面内容为PDF
   * @param selector - CSS选择器
   * @param options - PDF导出配置
   */
  const exportBySelector = async (
    selector: string | HTMLElement,
    options: PDFExportOptions = {}
  ): Promise<PDFExportResult> => {
    if (typeof window === 'undefined') {
      return {
        success: false,
        filename: '',
        error: 'PDF导出功能仅在浏览器环境中可用'
      }
    }
    if(typeof selector === 'string'){
      const element = document.querySelector(selector) as HTMLElement
      return exportToPDF(element, options)
    }
    return exportToPDF(selector, options)
  }

  /**
   * 导出组件内容为PDF
   * @param componentRef - Vue组件引用
   * @param options - PDF导出配置
   */
  const exportComponent = async (
    componentRef: any,
    options: PDFExportOptions = {}
  ): Promise<PDFExportResult> => {
    const element = componentRef?.$el || componentRef
    return exportToPDF(element, options)
  }

  return {
    isGenerating,
    progress,
    exportToPDF,
    exportBySelector,
    exportComponent,
  }
}